//配置路由的地方
import Vue from 'vue'
import VueRouter from 'vue-router'
//引入routes
import routes from './routes'
//使用插件
Vue.use(VueRouter)

//重写push方法
//必须解决，不然报Uncaught (in promise) NavigationDuplicated:错误
let originpush = VueRouter.prototype.push
VueRouter.prototype.push = function (location, resolve, reject) {
  if (resolve || reject) {
    originpush.call(this, location, resolve, reject)
  } else {
    originpush.call(this, location, () => { }, () => { })
  }
}

//重写replace方法
let originreplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function (location, resolve, reject) {
  if (resolve || reject) {
    originreplace.call(this, location, resolve, reject)
  } else {
    originreplace.call(this, location, () => { }, () => { })
  }
}

//配置路由
const router = new VueRouter({
  //配置路由
  routes,
  //配置滚动条，在跳转路由后滚动条出现在顶部
  scrollBehavior(to, from, savedPosition) {
    return { x: 0, y: 0 }
  }
})
router.beforeEach((to,from,next)=>{
  // next()
  let userToken = localStorage.getItem('USER_TOKEN')
  if(userToken){
    if(to.path == '/login' || to.path == '/register'){
      next('/home')
    }else{
      next()
    }
  }else{
    let forbidpath = ['/center/myorder','/pay','/trade','/shopcart','/paysuccess']
    if(forbidpath.indexOf(to.path)==-1){
      // console.log(forbidpath.indexOf(to.path));
      next()
    }else{
      alert('请先登录！')
      next('/login?redirect='+to.path)
    }
  }
})
export default router